// 硬件抽象层 - 直接访问硬件

/// 端口 I/O (x86)
pub inline fn outb(port: u16, value: u8) void {
    asm volatile ("outb %[value], %[port]"
        :
        : [value] "{al}" (value),
          [port] "N{dx}" (port),
    );
}

pub inline fn inb(port: u16) u8 {
    return asm volatile ("inb %[port], %[result]"
        : [result] "={al}" (-> u8),
        : [port] "N{dx}" (port),
    );
}

/// 串口输出（用于调试）
pub const SerialPort = struct {
    const COM1: u16 = 0x3F8;
    
    pub fn init() void {
        outb(COM1 + 1, 0x00); // 禁用中断
        outb(COM1 + 3, 0x80); // 启用 DLAB
        outb(COM1 + 0, 0x03); // 设置波特率 (低位)
        outb(COM1 + 1, 0x00); // 设置波特率 (高位)
        outb(COM1 + 3, 0x03); // 8 位，无校验，1 停止位
        outb(COM1 + 2, 0xC7); // 启用 FIFO
        outb(COM1 + 4, 0x0B); // IRQs enabled, RTS/DSR set
    }
    
    pub fn write_byte(byte: u8) void {
        // 等待发送缓冲区空闲
        while ((inb(COM1 + 5) & 0x20) == 0) {}
        outb(COM1, byte);
    }
    
    pub fn write(bytes: []const u8) void {
        for (bytes) |byte| {
            write_byte(byte);
        }
    }
};

/// VGA 文本模式输出
pub const VGA = struct {
    const VGA_BUFFER: usize = 0xB8000;
    const WIDTH: usize = 80;
    const HEIGHT: usize = 25;
    
    var row: usize = 0;
    var col: usize = 0;
    
    pub fn clear() void {
        const buffer: [*]volatile u16 = @ptrFromInt(VGA_BUFFER);
        var i: usize = 0;
        while (i < WIDTH * HEIGHT) : (i += 1) {
            buffer[i] = 0x0F00; // 黑底白字空格
        }
        row = 0;
        col = 0;
    }
    
    pub fn write_byte(byte: u8) void {
        const buffer: [*]volatile u16 = @ptrFromInt(VGA_BUFFER);
        
        if (byte == '\n') {
            col = 0;
            row += 1;
        } else {
            const index = row * WIDTH + col;
            buffer[index] = 0x0F00 | byte;
            col += 1;
        }
        
        if (col >= WIDTH) {
            col = 0;
            row += 1;
        }
        
        if (row >= HEIGHT) {
            row = 0; // 简单处理：回到顶部
        }
    }
    
    pub fn write(bytes: []const u8) void {
        for (bytes) |byte| {
            write_byte(byte);
        }
    }
};

/// 定时器（PIT - Programmable Interval Timer）
pub const Timer = struct {
    const PIT_CHANNEL0: u16 = 0x40;
    const PIT_COMMAND: u16 = 0x43;
    
    pub fn init(frequency: u32) void {
        const divisor: u16 = @intCast(1193180 / frequency);
        
        outb(PIT_COMMAND, 0x36); // Channel 0, rate generator
        outb(PIT_CHANNEL0, @intCast(divisor & 0xFF));
        outb(PIT_CHANNEL0, @intCast((divisor >> 8) & 0xFF));
    }
};
